/*
 * Created on 2005-4-11
 *
 */
package com.hd123.rumba.action.impex;

import java.util.Date;
import java.util.Iterator;

import net.sf.hibernate.Transaction;

import com.hd123.rumba.domain.IDomainMgr;
import com.hd123.rumba.exception.BusinessException;
import com.hd123.rumba.impex.ExportCondition;
import com.hd123.rumba.impex.ImpexLog;
import com.hd123.rumba.impex.ImpexMgr;
import com.hd123.rumba.impex.Indicator;
import com.hd123.rumba.request.Action;
import com.hd123.rumba.request.ActionAbstractImpl;
import com.hd123.rumba.request.ActionConstants;
import com.hd123.rumba.runtime.HibernateSession;
import com.hd123.rumba.runtime.NamingMgr;
import com.hd123.rumba.sql.ResultPage;
import com.hd123.rumba.sql.SQLSubquery;

/**
 * @author caili
 */
public class ViewLog extends ActionAbstractImpl implements Action {

  public String execute() throws Exception {
    String startnode = (String) dd.getFormValue("start");
    String url = ActionConstants.NOTIMPLEMENTED;
    if (startnode == null)
      startnode = "listIndicator";
    if (startnode.equals("listIndicator"))
      url = executeWithPermission("listIndicator",ImpexLog.PERMISSION_VIEW);
    else if (startnode.equals("listLog"))
      url = executeWithPermission("listLog",ImpexLog.PERMISSION_VIEW);
    if (startnode.equals("queryIndicator"))
      url = executeWithPermission("queryIndicator",ImpexLog.PERMISSION_VIEW);
    else if (startnode.equals("queryLog"))
      url = executeWithPermission("queryLog",ImpexLog.PERMISSION_VIEW);
    else if (startnode.equals("dispatch")) {
      if (dd.getFormValues().containsKey("listIndicator"))
        url = executeWithPermission("listIndicator",ImpexLog.PERMISSION_VIEW);
      else if (dd.getFormValues().containsKey("queryIndicator"))
        url = executeWithPermission("queryIndicator",ImpexLog.PERMISSION_VIEW);
      else if (dd.getFormValues().containsKey("listLog"))
        url = executeWithPermission("listLog",ImpexLog.PERMISSION_VIEW);
      else if (dd.getFormValues().containsKey("queryLog"))
        url = executeWithPermission("queryLog",ImpexLog.PERMISSION_VIEW);
      else if (dd.getFormValues().containsKey("setCondition"))
        url = executeWithPermission("setCondition",ImpexLog.PERMISSION_VIEW);
      else if (dd.getFormValues().containsKey("deleteSelectedLogs"))
        url = executeWithPermission("deleteSelectedLogs",ImpexLog.PERMISSION_DELETE);
      else
        url = paging();
    }
    return url;
  }

  protected final String TEMPLATE_LOGLIST = "rumba/impex/LogsList.jsp";
  protected final String TEMPLATE_LIST = "rumba/impex/IndicatorsList.jsp";

  protected String paging(int page) throws Exception {
    if ("logs".equals((String) dd.getFormValue("pageInfo_id")))
      return logPaging(page);
    else
      return indicatorPaging(page);
  }

  protected String indicatorPaging(int page) throws Exception {
    dd.validateFormValue("cond_lastActionTimeFrom",
        "Date(yyyy-MM-dd HH:mm:ss;yyyy-MM-dd HH:mm;yyyy-MM-dd", false);
    dd.validateFormValue("cond_lastActionTimeTo",
        "Date(yyyy-MM-dd HH:mm:ss;yyyy-MM-dd HH:mm;yyyy-MM-dd", false);
    if (!dd.isFormValid()) {
      dd.setWorkingTemplate(TEMPLATE_LIST);
      return ActionConstants.APPLICATIONFRAME;
    }
    SQLSubquery sq = new SQLSubquery();
    sq.addSelect("o");
    sq.addFrom("Indicator o");
    sq.addWhere("1=1");
    IDomainMgr domainMgr = (IDomainMgr) NamingMgr.getInstance().lookupMgr(IDomainMgr.class);
    if (!dd.getCurrentDomain().equals(domainMgr.getRootDomain()))
      sq.addWhere(" and o.counterPart.upperDomain = ?", dd.getCurrentDomain());
    //sq.addWhere("o.domain.uuid=?", dd.getCurrentDomain().getUuid());
    if (!"all".equals((String) dd.getFormValue("cond_object")))
      sq.addWhere("and o.object = ?", dd.getFormValue("cond_object"));
    sq.addWhere("and o.counterPart.code like ?", dd.getFormValue("cond_counterPart"),
        SQLSubquery.WC_BOTH);
    if (dd.getFormValue("cond_action") == null)
      dd.putFormValue("cond_action", "export");
    if (!"all".equals((String) dd.getFormValue("cond_action")))
      sq.addWhere("and o.action = ?", dd.getFormValue("cond_action"));
    sq
        .addWhere("and o.lastActionTime >= ?", dd.getValidFormValues().get(
            "cond_lastActionTimeFrom"));
    sq.addWhere("and p.lastActionTime <= ?", dd.getValidFormValues().get("cond_lastActionTimeTo"));
    String sortField = (String) dd.getFormValue("cond_sort_field");
    if (sortField == null)
      sortField = "o.object";
    String sortOrder = (String) dd.getFormValue("cond_sort_order");
    if (sortOrder == null)
      sortOrder = "asc";
    sq.addOrder(sortField, sortOrder);
    ResultPage rp = ResultPage.createHibernateResultPage(HibernateSession.getSession(), sq, 15,
        page);
    rp.setId("indicators");
    dd.put("indicators", rp.getContentList());
    dd.put("pageInfo", rp);
    dd.setWorkingTemplate(TEMPLATE_LIST);
    return ActionConstants.APPLICATIONFRAME;
  }

  public String listIndicator() throws Exception {
    dd.putFormValue("PageNumber_0", "0");
    dd.putFormValue("pageInfo_id", "indicators");
    return paging();
  }

  public String queryIndicator() throws Exception {
    dd.putFormValue("PageNumber_0", "0");
    dd.putFormValue("pageInfo_id", "indicators");
    return paging();
  }

  public String logPaging(int page) throws Exception {
    dd.validateFormValue("cond_startTimeFrom",
        "Date(yyyy-MM-dd HH:mm:ss;yyyy-MM-dd HH:mm;yyyy-MM-dd", false);
    dd.validateFormValue("cond_startTimeTo",
        "Date(yyyy-MM-dd HH:mm:ss;yyyy-MM-dd HH:mm;yyyy-MM-dd", false);
    if (!dd.isFormValid()) {
      dd.setWorkingTemplate(TEMPLATE_LOGLIST);
      return ActionConstants.APPLICATIONFRAME;
    }

    String indUuid = (String) dd.getFormValue("ind_uuid");
    if (indUuid == null) {
      dd.putFormValue("currentObject", "全部");
    } else {
      ImpexMgr impexMgr = ImpexMgr.getInstance();
      Indicator ind = impexMgr.getIndicator(indUuid);
      dd.putFormValue("currentObject", ind.getObject());
    }

    SQLSubquery sq = new SQLSubquery();
    sq.addSelect("o");
    sq.addFrom("ImpexLog o");
    sq.addWhere("1=1");
    sq.addWhere("and o.indicator.uuid=?", dd.getFormValue("ind_uuid"));
    sq.addWhere("and o.startTime >= ?", dd.getValidFormValues().get("cond_startTimeFrom"));
    sq.addWhere("and o.startTime <= ?", dd.getValidFormValues().get("cond_startTimeTo"));
    String sortField = (String) dd.getFormValue("cond_sort_field");
    if (sortField == null)
      sortField = "o.startTime";
    String sortOrder = (String) dd.getFormValue("cond_sort_order");
    if (sortOrder == null)
      sortOrder = "desc";
    sq.addOrder(sortField, sortOrder);
    ResultPage rp = ResultPage.createHibernateResultPage(HibernateSession.getSession(), sq, 15,
        page);
    rp.setId("logs");
    dd.put("logs", rp.getContentList());
    dd.put("pageInfo", rp);
    dd.setWorkingTemplate(TEMPLATE_LOGLIST);
    return ActionConstants.APPLICATIONFRAME;
  }

  public String listLog() throws Exception {
    dd.putFormValue("PageNumber_0", "0");
    dd.putFormValue("pageInfo_id", "logs");
    return paging();
  }

  public String queryLog() throws Exception {
    dd.putFormValue("PageNumber_0", "0");
    dd.putFormValue("pageInfo_id", "logs");
    return paging();
  }

  public String setCondition() throws Exception {
    dd.validateFormValue("set_cond_time", "Date(yyyy-MM-dd HH:mm:ss;yyyy-MM-dd HH:mm;yyyy-MM-dd",
        false);
    if (!dd.isFormValid()) {
      dd.setWorkingTemplate(TEMPLATE_LOGLIST);
      return ActionConstants.APPLICATIONFRAME;
    }

    ExportCondition ec = new ExportCondition();
    ec.setTime((Date) dd.getValidFormValues().get("set_cond_time"));
    ec.setCode((String) dd.getFormValue("set_cond_id"));

    Iterator uuids = dd.createFormSelectedValuesIterator("selectedUuids");
    if (uuids.hasNext()) {
      ImpexMgr impexMgr = ImpexMgr.getInstance();
      Transaction tx = HibernateSession.beginTransaction();
      int count = 0;
      try {
        while (uuids.hasNext()) {
          Indicator indicator = impexMgr.getIndicator((String) uuids.next());
          if (indicator.getAction().equals(Indicator.EXPORT)) {
            indicator.setExportCondition(ec);
            impexMgr.saveIndicator(indicator);
            ++count;
          }
        }
        HibernateSession.commit(tx);
        dd.addHint(count + "笔导出日志已被重新设置条件.");
      } catch (Exception e) {
        HibernateSession.rollback(tx);
        if (e instanceof BusinessException) {
          dd.addErrorText(e.getMessage());
          return paging();
        } else {
          throw e;
        }
      }
    }
    return paging();
  }

  public String deleteSelectedLogs() throws Exception {
    Iterator uuids = dd.createFormSelectedValuesIterator("selectedUuids");
    if (uuids.hasNext()) {
      ImpexMgr impexMgr = ImpexMgr.getInstance();
      Transaction tx = HibernateSession.beginTransaction();
      int count = 0;
      try {
        while (uuids.hasNext()) {
          ImpexLog log = impexMgr.getImpexLog((String) uuids.next());
          impexMgr.removeImpexLog(log);
          ++count;
        }
        HibernateSession.commit(tx);
        dd.addHint(count + "条记录已被删除.");
      } catch (Exception e) {
        HibernateSession.rollback(tx);
        if (e instanceof BusinessException) {
          dd.addErrorText(e.getMessage());
          return paging();
        } else {
          throw e;
        }
      }
    }
    return paging();
  }
}
